package flc.ast.activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.SeekBar;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.core.BasePopupView;
import com.stark.picselect.entity.SelectMediaEntity;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.PlayListAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.databinding.ActivityPlayLandscapeBinding;
import flc.ast.dialog.RenameDialog;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.TimeUtil;

public class PlayLandscapeActivity extends BaseAc<ActivityPlayLandscapeBinding> {

    public static List<SelectMediaEntity> listPlay = new ArrayList<>();//播放列表
    public static int type = 0;//0本地 1视频相册 2收藏视频
    public static int selPlayPos = 0;
    private PlayListAdapter listAdapter;
    private String videoPath = "";
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeftText.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mDataBinding.sbPlay.setProgress(Integer.parseInt(TimeUtils.millis2String(mDataBinding.videoView.getCurrentPosition(), "ss")));
            mHandler.postDelayed(this, 500);
        }
    };
    private boolean isShow = true;
    private boolean isLock = false;
    private int speedKind = 0;
    private float selSpeed = 1.0f;

    @Override
    protected int onCreate() {
        return R.layout.activity_play_landscape;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPlayBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.videoView.setOnClickListener(this);
        mDataBinding.rlPlayMore.setOnClickListener(this);
        mDataBinding.rlPlayList.setOnClickListener(this);
        mDataBinding.tvPlayClear.setOnClickListener(this);
        mDataBinding.rlPlayInfo.setOnClickListener(this);

        mDataBinding.ivPlayInfo.setOnClickListener(this);
        mDataBinding.ivPlayList.setOnClickListener(this);
        mDataBinding.ivPlayMore.setOnClickListener(this);
        mDataBinding.ivPlayShare.setOnClickListener(this);
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivPlayLock.setOnClickListener(this);
        mDataBinding.tvPlaySpeed.setOnClickListener(this);

        mDataBinding.ivPlayLast.setOnClickListener(this);
        mDataBinding.ivPlayNext.setOnClickListener(this);

        mDataBinding.rvPlayList.setLayoutManager(new LinearLayoutManager(mContext));
        listAdapter = new PlayListAdapter(mContext);
        listAdapter.setOnItemClickListener(new PlayListAdapter.OnItemClickListener() {
            @Override
            public void onClick(SelectMediaEntity bean, int position) {
                listPlay.get(selPlayPos).setChecked(false);
                listAdapter.notifyItemChanged(selPlayPos);
                selPlayPos = position;
                listPlay.get(position).setChecked(true);
                listAdapter.notifyItemChanged(position);
                mDataBinding.tvPlayName.setText(listPlay.get(position).getMediaName());
                setPlayer();
            }

            @Override
            public void onClickDelete(SelectMediaEntity bean, int position) {
                listPlay.remove(position);
                listPlay.get(selPlayPos).setChecked(false);
                listAdapter.notifyItemChanged(selPlayPos);
                selPlayPos = 0;
                listPlay.get(0).setChecked(true);
                listAdapter.notifyItemChanged(0);
                mDataBinding.tvPlayName.setText(listPlay.get(0).getMediaName());
                setPlayer();
            }
        });
        listPlay.get(selPlayPos).setChecked(true);
        listAdapter.setmDatas(listPlay);
        mDataBinding.rvPlayList.setAdapter(listAdapter);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.videoView:
                if (isLock) return;
                isShow = !isShow;
                mDataBinding.ivPlayLock.setVisibility(isShow ? View.VISIBLE : View.GONE);
                mDataBinding.rlPlayTopView.setVisibility(isShow ? View.VISIBLE : View.GONE);
                mDataBinding.llPlayBottomView.setVisibility(isShow ? View.VISIBLE : View.GONE);
                break;
            case R.id.ivPlayShare://分享
                IntentUtil.shareVideo(mContext, listPlay.get(selPlayPos).getPath());
                break;
            case R.id.ivPlayMore://更多
                mDataBinding.rlPlayMore.setVisibility(View.VISIBLE);
                break;
            case R.id.rlPlayMore:
                mDataBinding.rlPlayMore.setVisibility(View.GONE);
                break;
            //更多
            case R.id.tvRename://重命名
                showRenameDialog(selPlayPos);
                mDataBinding.rlPlayMore.setVisibility(View.GONE);
                break;
            case R.id.tvFolder://存入加密
                String filePath = FileUtil.generateFilePath(Content.myPrivacyVideo, "." + FileUtils.getFileExtension(listPlay.get(selPlayPos).getPath()));
                FileUtils.copy(listPlay.get(selPlayPos).getPath(), filePath);
                mDataBinding.rlPlayMore.setVisibility(View.GONE);
                break;
            case R.id.tvDelete://删除
                if (type == 0) {
                    getDeletePermission();
                } else if (type == 1) {
                    deleteAlbum();
                } else if (type == 2) {
                    deleteCollect();
                }
                mDataBinding.rlPlayMore.setVisibility(View.GONE);
                break;
            case R.id.ivPlayList://播放列表
                mDataBinding.rlPlayList.setVisibility(View.VISIBLE);
                break;
            case R.id.rlPlayList:
                mDataBinding.rlPlayList.setVisibility(View.GONE);
                break;
            case R.id.tvPlayClear://清空
                listPlay.clear();
                listAdapter.setmDatas(listPlay);
                listAdapter.notifyDataSetChanged();
                selPlayPos = 0;
                break;
            case R.id.ivPlayInfo://信息
                getInfo();
                mDataBinding.rlPlayInfo.setVisibility(View.VISIBLE);
                break;
            case R.id.rlPlayInfo:
                mDataBinding.rlPlayInfo.setVisibility(View.GONE);
                break;
            case R.id.ivPlayStart://暂停/播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abof);
                    mDataBinding.videoView.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azantin);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivPlayLock://锁定
                isLock = !isLock;
                mDataBinding.ivPlayLock.setImageResource(isLock ? R.drawable.asuodin : R.drawable.aweisuod);
                mDataBinding.rlPlayTopView.setVisibility(isLock ? View.GONE : View.VISIBLE);
                mDataBinding.llPlayBottomView.setVisibility(isLock ? View.GONE : View.VISIBLE);
                break;
            case R.id.ivPlayLast://上一个
                if (selPlayPos > 0) {
                    listPlay.get(selPlayPos).setChecked(false);
                    listAdapter.notifyItemChanged(selPlayPos);
                    selPlayPos--;
                    listPlay.get(selPlayPos).setChecked(true);
                    listAdapter.notifyItemChanged(selPlayPos);
                    mDataBinding.tvPlayName.setText(listPlay.get(selPlayPos).getMediaName());
                    setPlayer();
                } else {
                    ToastUtils.showShort(getString(R.string.last_tip));
                }
                break;
            case R.id.ivPlayNext://下一个
                if (selPlayPos >= listPlay.size() - 1) {
                    ToastUtils.showShort(getString(R.string.next_tip));
                } else {
                    listPlay.get(selPlayPos).setChecked(false);
                    listAdapter.notifyItemChanged(selPlayPos);
                    selPlayPos++;
                    listPlay.get(selPlayPos).setChecked(true);
                    listAdapter.notifyItemChanged(selPlayPos);
                    mDataBinding.tvPlayName.setText(listPlay.get(selPlayPos).getMediaName());
                    setPlayer();
                }
                break;
            case R.id.tvPlaySpeed://变速
                if (speedKind == 0) {
                    speedKind = 1;
                    selSpeed = 2.0f;
                    mDataBinding.tvPlaySpeed.setText("2x");
                } else if (speedKind == 1) {
                    speedKind = 2;
                    selSpeed = 0.5f;
                    mDataBinding.tvPlaySpeed.setText("0.5x");
                } else if (speedKind == 2) {
                    speedKind = 0;
                    selSpeed = 1f;
                    mDataBinding.tvPlaySpeed.setText("1x");
                }
                setSpeed();
                break;
        }
    }

    @Override
    protected void initData() {
        if (listPlay == null || listPlay.size() == 0) return;
        mDataBinding.tvPlayName.setText(listPlay.get(selPlayPos).getMediaName());
        //设置播放器
        setPlayer();
    }

    //设置播放速度
    private void setSpeed() {
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onPrepared(MediaPlayer mp) {
                PlaybackParams playbackParams = mp.getPlaybackParams();
                playbackParams.setSpeed(selSpeed);
                mp.setPlaybackParams(playbackParams);
                mDataBinding.ivPlayStart.setImageResource(R.drawable.azantin);
                startTime();
            }
        });
    }

    //设置播放器
    private void setPlayer() {
        if (listPlay.size() == 0) {
            ToastUtils.showShort(R.string.no_data_hint);
            return;
        }
        mHandler = new Handler();
        videoPath = listPlay.get(selPlayPos).getPath();
        videoLength = MediaUtil.getDuration(videoPath);
        //设置seekbar
        mDataBinding.tvPlayLeftText.setText("00:00");
        mDataBinding.tvPlayRightText.setText("/" + TimeUtil.getMmss(videoLength));
        mDataBinding.sbPlay.setMax(Integer.parseInt(TimeUtils.millis2String(videoLength, "ss")));
        mDataBinding.sbPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDataBinding.videoView.seekTo(seekBar.getProgress());
            }
        });
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                if (listPlay.size() == 0) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abof);
                    return;
                }
                if (selPlayPos == listPlay.size() - 1) {
                    mDataBinding.tvPlayLeftText.setText("00:00");
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abof);
                    mDataBinding.sbPlay.setProgress(0);
                    mp.seekTo(1);
                    stopTime();
                } else {
                    selPlayPos++;
                    mDataBinding.tvPlayName.setText(listPlay.get(selPlayPos).getMediaName());
                    setPlayer();
                }
            }
        });
        //开始播放视频
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azantin);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivPlayStart.setImageResource(R.drawable.abof);
        mDataBinding.videoView.pause();
        stopTime();
    }

    private void showRenameDialog(int position) {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.title = getString(R.string.file_rename);
        dialog.hint = getString(R.string.please_input_folder_name_text);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(listPlay.get(position).getPath(), name + "." + FileUtils.getFileExtension(listPlay.get(position).getPath()));
                mDataBinding.tvPlayName.setText(name);
            }
        });
        dialog.show();
    }

    //获取权限
    private void getDeletePermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_all_storage_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        delete();
                    }
                })
                .request();
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        mContext.getContentResolver().delete(Uri.parse(listPlay.get(selPlayPos).getUri()), null, null);
                        listPlay.remove(selPlayPos);
                        listAdapter.setmDatas(listPlay);
                        listAdapter.notifyDataSetChanged();
                        selPlayPos = 0;
                        setPlayer();
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void getInfo() {
        mDataBinding.tvFileName.setText(FileUtils.getFileName(videoPath));
        mDataBinding.tvLocation.setText(videoPath);
        mDataBinding.tvSize.setText(FileUtils.getSize(videoPath));
        mDataBinding.tvCreateTime.setText(TimeUtils.millis2String(FileUtils.getFileLastModified(videoPath), "yyyy年MM月dd日 HH:mm:ss"));
        mDataBinding.tvFormat.setText(FileUtils.getFileName(videoPath).substring(FileUtils.getFileName(videoPath).lastIndexOf(".") + 1));
        mDataBinding.tvResolution.setText(MediaUtil.getMediaMetadataInfo(videoPath).getWidth() + " x " + MediaUtil.getMediaMetadataInfo(videoPath).getHeight());
        mDataBinding.tvDuration.setText(TimeUtils.millis2String(MediaUtil.getDuration(videoPath), "mm:ss"));
    }

    //删除相册图片
    private void deleteAlbum() {
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            for (MyAlbumBean bean : listSp) {
                if (bean.getId().equals(VideoAlbumActivity.albumId)) {
                    for (SelectMediaEntity selectMediaEntity : bean.getList()) {
                        if (selectMediaEntity.getPath().equals(listPlay.get(selPlayPos).getPath())) {
                            bean.getList().remove(selectMediaEntity);
                            break;
                        }
                    }
                }
            }
            AppSpUtils.saveAlbumList(listSp);
        }
        listPlay.remove(selPlayPos);
        selPlayPos = 0;
        setPlayer();
    }

    //删除收藏视频
    private void deleteCollect() {
        List<SelectMediaEntity> listSp = AppSpUtils.getCollectList();
        if (listSp != null && listSp.size() > 0) {
            listSp.remove(selPlayPos);
            AppSpUtils.saveCollectList(listSp);
        }
        listPlay.remove(selPlayPos);
        selPlayPos = 0;
        setPlayer();
    }

}